package com.nit.lab.service.basic.impl;


import com.nit.lab.dto.basic.WjmDTO;
import com.nit.lab.dto.utils.PagingDTO;
import com.nit.lab.dto.utils.TableReqDTO;
import com.nit.lab.dto.utils.TableRspDTO;
import com.nit.lab.entity.basic.WjmEntity;
import com.nit.lab.mapper.basic.WjmMapper;
import com.nit.lab.service.basic.WjmService;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class WjmServiceImpl implements WjmService {

    @Autowired(required = false)
    private WjmMapper wjmMapper;

    @Override
    public TableRspDTO list4Table(TableReqDTO tableReqDTO) throws Exception {
        Long count = wjmMapper.count4Table(
                tableReqDTO.parseQueryParam("wjmName"),
                tableReqDTO.parseQueryParam("wjmTel"));

        PagingDTO pagingDTO = new PagingDTO(
                tableReqDTO.getPageNo(),
                tableReqDTO.getPageSize(),
                count,
                wjmMapper.list4Table(
                        tableReqDTO.getStart(),
                        tableReqDTO.getPageSize(),
                        tableReqDTO.parseQueryParam("wjmName"),
                        tableReqDTO.parseQueryParam("wjmTel"),
                        tableReqDTO.getSortField(),
                        tableReqDTO.getSortOrder()));
        TableRspDTO tableRspDTO = new TableRspDTO(pagingDTO);
        return tableRspDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer add(WjmDTO wjmDTO) throws Exception {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        WjmEntity wjmEntity = mapperFactory.getMapperFacade().map(wjmDTO, WjmEntity.class);
        return wjmMapper.add(wjmEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer update(WjmDTO wjmDTO) throws Exception {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        WjmEntity wjmEntity = mapperFactory.getMapperFacade().map(wjmDTO, WjmEntity.class);

        return wjmMapper.update(wjmEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer remove(String wjmIds) throws Exception {
        String[] arrayWjmId = wjmIds.split(",");
        for (int i = 0; i < arrayWjmId.length; i++) {
            wjmMapper.remove(Long.parseLong(arrayWjmId[i]));
        }
        return arrayWjmId.length;
    }
}
